using System;
using Microsoft.SPOT;

namespace LBNHelpers
{
	public static class Convertion
	{
		public static int From(byte[] data)
		{
			if (data.Length > 4) throw new ArgumentException("data array must not exceed 4 bytes");

			int v=0;
			switch (data.Length)
			{
				case 4:
					v = (((int)data[0]) << 0) | (((int)data[1]) << 8) | (((int)data[2]) << 16) | (((int)data[3]) << 24);
					break;
				case 3:
					v = (((int)data[0]) << 0) | (((int)data[1]) << 8) | (((int)data[2]) << 16);
					break;
				case 2:
					v = (((int)data[0]) << 0) | (((int)data[1]) << 8);
					break;
				case 1:
					v = (int)data[0];
					break;
			}
			return v;
		}

		public static string ToString(byte[] data)
		{
			return new string(System.Text.UTF8Encoding.UTF8.GetChars(data));			
		}

		public static void To(int v, ref byte[] data)
		{
			if (data == null)		data = new byte[4];

			var l = data.Length;
			if (l>0)	data[0] = (byte)(v);
			if (l>1)	data[1] = (byte) (v >> 8);
			if (l>2)	data[2] = (byte) (v >> 16);
			if (l>3)	data[3] = (byte) (v >> 24);
		}

		public static void To(long v, ref byte[] data)
		{
			if (data == null) data = new byte[4];

			var l = data.Length;
			if (l > 0) data[0] = (byte)(v);
			if (l > 1) data[1] = (byte)(v >> 8);
			if (l > 2) data[2] = (byte)(v >> 16);
			if (l > 3) data[3] = (byte)(v >> 24);
		}

		public static byte[] To(int v)
		{
			byte[] data = null;
			To(v, ref data);
			return data;
		}

		public static byte[] To(long v)
		{
			byte[] data = null;
			To(v, ref data);
			return data;
		}
	}
}
